package cn.net.cfss.fgbp.provider.console.spi;

import cn.net.cfss.fgbp.api.console.constant.DeleteFlagEnum;
import cn.net.cfss.fgbp.api.console.dto.SysUserMenufieldDto;
import cn.net.cfss.fgbp.api.console.inte.ISysUserMenufieldService;
import cn.net.cfss.fgbp.base.constant.ErrCodeEnum;
import cn.net.cfss.fgbp.base.except.CodeException;
import cn.net.cfss.fgbp.base.service.FeignBaseService;
import cn.net.cfss.fgbp.provider.console.biz.SysUserMenufieldBiz;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * @author wutao
 * @version 1.0
 * @date 2021/3/18 16:07
 */
@RestController
@Slf4j
public class SysUserMenufieldSpi extends FeignBaseService implements ISysUserMenufieldService {

    @Autowired
    private SysUserMenufieldBiz sysUserMenufieldBiz;

    @Override
    public SysUserMenufieldDto selectOne(SysUserMenufieldDto sysUserMenufieldDto) {
        sysUserMenufieldDto.setDeleteFlag(DeleteFlagEnum.NOT_DEL);
        return sysUserMenufieldBiz.selectOne(sysUserMenufieldDto);
    }

    @Override
    public SysUserMenufieldDto addOrUpdate(SysUserMenufieldDto sysUserMenufieldDto) {
        String menuKey = sysUserMenufieldDto.getMenuKey();
        Long userId = getUserId();

        SysUserMenufieldDto search = new SysUserMenufieldDto();
        search.setDeleteFlag(DeleteFlagEnum.NOT_DEL);
        search.setMenuKey(menuKey);
        search.setUserId(userId);

        List<SysUserMenufieldDto> sysUserMenufieldDtos = sysUserMenufieldBiz.selectList(search);
        if (sysUserMenufieldDtos.size() > 1) {
            log.error("user:{},menuKey:{}，查询出多条数据", userId, menuKey);
            throw new CodeException(ErrCodeEnum.ERR, "数据异常");
        }
        if (sysUserMenufieldDtos.size() == 1) {
            //更新
            sysUserMenufieldDto.setId(sysUserMenufieldDtos.get(0).getId());
            sysUserMenufieldDto.setUpdateBy(getUserId());
            sysUserMenufieldDto.setUpdateTime(new Date());
            sysUserMenufieldBiz.updateSelectiveById(sysUserMenufieldDto);
            return sysUserMenufieldDto;
        }
        //没有查询到，新增
        sysUserMenufieldDto.setId(sysUserMenufieldBiz.getUID());
        sysUserMenufieldDto.setUserId(userId);
        sysUserMenufieldDto.setDeleteFlag(DeleteFlagEnum.NOT_DEL);
        sysUserMenufieldDto.setCreateBy(getUserId());
        sysUserMenufieldDto.setUpdateBy(getUserId());
        sysUserMenufieldDto.setCreateTime(new Date());
        sysUserMenufieldDto.setUpdateTime(new Date());
        sysUserMenufieldBiz.insert(sysUserMenufieldDto);

        return sysUserMenufieldDto;
    }
}
